package com.jh.paymentchannel.helipay.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.service.SpendService;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.ump.exception.VerifyException;
import com.jh.paymentchannel.util.ump.paygate.v40.Mer2Plat_v40;
import com.jh.paymentchannel.util.ump.paygate.v40.Plat2Mer_v40;
import com.jnewsdk.util.SignUtil;

import net.sf.json.JSONObject;


@Controller
public class HLCallBackService {

	private static final Logger log = LoggerFactory.getLogger(HLCallBackService.class);
	
	@Autowired
	Util util;
	@Autowired
    SpendService ss;
	@Autowired
	HLRegisterService rs;

	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/hl/notify_call")
	public @ResponseBody void notifycall(HttpServletRequest request, HttpServletResponse response) throws IOException{
		log.info("into HLCallBackService  ================ "+request.getParameterMap().toString());
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
		Map<String, String> paramMap = SignUtil.parseParam(request);
		log.info("paramMap=============" + paramMap);
		JSONObject jsonInfo = JSONObject.fromObject(paramMap);
		log.info("jsonInfo=============" + jsonInfo.toString());
	       String resString = "fail" ;
	       if("0000".equals(jsonInfo.getString("rt2_retCode"))){
	    	   String trade_no = jsonInfo.getString("rt6_serialNumber");
	    	   String ordercode = jsonInfo.getString("rt5_orderId");
	    	   String orderstatus = jsonInfo.getString("rt9_orderStatus");
	    	   String bindId = jsonInfo.getString("rt10_bindId");
	    	   String orderAmount = jsonInfo.getString("rt8_orderAmount");
	    	   if("SUCCESS".equals(orderstatus)) {
	    		   Object result = ss.findById(ordercode);
	    		   JSONObject obj = JSONObject.fromObject(result);
	    		   log.info("============="+obj+"=============");
	    		   if(obj.containsKey("result")) {
	    			   JSONObject jsonresult = obj.getJSONObject("result");
	    			   String message = jsonresult.getString("message");
	    			   if(!"成功".equals(message.trim())) {
	    				   result = ss.updateSpendsByOrderSon(ordercode, "SUCCESS", "3");
	    				   obj = JSONObject.fromObject(result);
	    	    		   log.info("============="+obj+"=============");
	    			   }
	    		   }
	    		  if(Float.valueOf(orderAmount)<Float.valueOf("3.00")) {
	    			  result = rs.updateExemption(request, bindId, "", "", "", "", "2");
	    			  obj = JSONObject.fromObject(result);
	    			  log.info("============="+obj+"=============");
	    		  }
	    	   }
	    	   
	    	   try {
				RestTemplate restTemplate=new RestTemplate();
				
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/update";
				
				/**根据的用户手机号码查询用户的基本信息*/
				MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("status", "1");
				requestEntity.add("third_code",   trade_no);
				requestEntity.add("order_code",   ordercode);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				
				/**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
				uri = util.getServiceUrl("transactionclear", "error url request!");
				url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				
				
				requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code",   ordercode);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				
				JSONObject jsonObject =  JSONObject.fromObject(result);
				if(jsonObject.containsKey("result")) {
					JSONObject resultObj  =  jsonObject.getJSONObject("result");
					String outMerOrdercode  =  resultObj.getString("outMerOrdercode");
					String orderdesc        =  resultObj.getString("desc");
					String phone            =  resultObj.getString("phone");
					String  tranamount      =  resultObj.getString("amount");
					String channelTag       =  resultObj.getString("channelTag");
					String notifyURL        =  resultObj.getString("outNotifyUrl");
					if(outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")){
						uri = util.getServiceUrl("channel", "error url request!");
						url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
						requestEntity  = new LinkedMultiValueMap<String, String>();
						requestEntity.add("merchant_no",  phone);
						requestEntity.add("amount",  tranamount);
						requestEntity.add("channel_tag",  channelTag);
						requestEntity.add("order_desc",  URLEncoder.encode(orderdesc, "UTF-8"));
						requestEntity.add("order_code",  outMerOrdercode);
						requestEntity.add("sys_order",   ordercode);
						requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
						result = restTemplate.postForObject(url, requestEntity, String.class);
					}
				}
	    	   }catch(Exception e) {
	    		   log.info("=============获取异常："+e.getMessage());
	    	   }
				resString = "SUCCESS" ;
	       }else if(jsonInfo.containsKey("status")&&"0".equals(jsonInfo.getString("status"))){
	    	   String ordercode = jsonInfo.getString("transactionId");
	    	   RestTemplate restTemplate=new RestTemplate();
				
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/update";
				
				/**根据的用户手机号码查询用户的基本信息*/
				MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("status", "1");
				requestEntity.add("third_code",   "");
				requestEntity.add("order_code",   ordercode);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				
				/**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
				uri = util.getServiceUrl("transactionclear", "error url request!");
				url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				
				
				requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code",   ordercode);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				
				JSONObject jsonObject =  JSONObject.fromObject(result);
				JSONObject resultObj  =  jsonObject.getJSONObject("result");
				String outMerOrdercode  =  resultObj.getString("outMerOrdercode");
				String orderdesc        =  resultObj.getString("desc");
				String phone            =  resultObj.getString("phone");
				String  tranamount      =  resultObj.getString("amount");
				String channelTag       =  resultObj.getString("channelTag");
				String notifyURL        =  resultObj.getString("outNotifyUrl");
				if(outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")){
					uri = util.getServiceUrl("channel", "error url request!");
					url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
					requestEntity  = new LinkedMultiValueMap<String, String>();
					requestEntity.add("merchant_no",  phone);
					requestEntity.add("amount",  tranamount);
					requestEntity.add("channel_tag",  channelTag);
					requestEntity.add("order_desc",  URLEncoder.encode(orderdesc, "UTF-8"));
					requestEntity.add("order_code",  outMerOrdercode);
					requestEntity.add("sys_order",   ordercode);
					requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
					result = restTemplate.postForObject(url, requestEntity, String.class);
				}
				resString = "SUCCESS" ;
	       }else {
	    	   if(jsonInfo.containsKey("rt5_orderId")) {
	    		   String ordercode = jsonInfo.getString("rt5_orderId");
	    		   Object result = ss.findById(ordercode);
	    		   JSONObject obj = JSONObject.fromObject(result);
	    		   log.info("============="+obj+"=============");
	    		   if(obj.containsKey("result")) {
	    			   JSONObject jsonresult = obj.getJSONObject("result");
	    			   String message = jsonresult.getString("message");
	    			   if("成功".equals(message.trim())) {
	    				   result = ss.updateSpendsByOrderSon(ordercode, "FAILED", "5");
	    				   obj = JSONObject.fromObject(result);
	    	    		   log.info("============="+obj+"=============");
	    			   }
	    		   }
	    	   }
	        	log.info("发生异常"+jsonInfo.getString("errMsg"));
	        	resString = "fail";
	        }
	       PrintWriter write = response.getWriter();
	       write.print(resString);
	       write.flush();
	       
	}
		
	
}
